﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Calculation = Sunboxsoft.ASMS.Client.Domain.Calculation;
using LocalService = Sunboxsoft.ASMS.Client.Domain.LocalService;
namespace Sunboxsoft.ASMS.Client.UI.Create
{
    public partial class CreateMaintenanceBillView : UserControl, IView
    {
        #region Property
        Promise _promise = new Promise();

        /// <summary>
        /// 选择预约单
        /// </summary>
        WebRef.VBookingBill _selectedBill = null;
        /// <summary>
        /// 客户
        /// </summary>
        WebRef.VCustomer selectCustomer = null;
        WebRef.ECustomer newCustomer = null;
        /// <summary>
        /// 选择客户车辆信息
        /// </summary>
        WebRef.VAutomobile entity = null;
        /// <summary>
        /// 服务项目
        /// </summary>
        List<WebRef.EMaintenanceBillServiceItem> listServiceItem = new List<WebRef.EMaintenanceBillServiceItem>();
        /// <summary>
        /// 选择商品
        /// </summary>
        List<WebRef.EMaintenanceBillMaterial> listMaterialItem = new List<WebRef.EMaintenanceBillMaterial>();
        /// <summary>
        /// 选择其他收费/优惠项目
        /// </summary>
        List<WebRef.EMaintenanceBillPayItem> listPayItem = new List<WebRef.EMaintenanceBillPayItem>();
        #endregion

        public CreateMaintenanceBillView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(ctlLookUpSalesManager, "受理人"));
            ValidationManager.Register(this, new Common.Validations.TextEditIsFloatNumber(txtKM, "当前里程", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(txtPickRemark, "接车备注", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(txtLPN, "车架号码", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(txtEngineNo, "发动机号", true));
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(lupInsuranceCompany, "保险公司"));
        }
        /// <summary>
        /// 从预约单列表点击接车派工按钮
        /// </summary>
        /// <param name="selectedBill"></param>
        public CreateMaintenanceBillView(WebRef.VBookingBill selectedBill)
            : this()
        {
            this._selectedBill = selectedBill;
        }

        #region IView 成员

        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("save", Resources.isOK, "保存", btnSave_Click));
        }

        public void Active(ViewActiveArgs args)
        {
            _promise.Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    ctlSearchLookUpEditOilMass.BindIntCodeTextItem(Domain.Constant.OilMass.EnumerateAll(), null, true);
                    _promise.Resolve();
                }));
            })
                .Then(() =>
            {
                lupInsuranceCompany.BindEMasterDataItem(_promise, Domain.Constant.MasterDataCodes.InsuranceCompany);
            }).Then(() =>
            {
                ctlLookUpSalesManager.BindVStaffPosition(_promise, Domain.Constant.StaffPosts.SalesManager);
            }).Then(() =>
            {
                this.BeginInvoke(new Action(() =>
                {
                    if (this._selectedBill != null)
                    {
                        GetSelectedBookBill();
                    }
                    _promise.Resolve();
                }));
            }).Then(() =>
            {
                this.repositoryItemSearchLookUpEditTechnician.BindVStaffPosition(this, _promise, Domain.Constant.StaffPosts.SalesManager);
            }).Then(() =>
            {
                this.repositoryItemSearchLookUpSalesManager.BindVStaffPosition(this, _promise, Domain.Constant.StaffPosts.SalesManager);
            })
            .Then(() =>
            {
                this.repositoryItemSearchLookUpEditGSalesManager.BindVStaffPosition(this, _promise, Domain.Constant.StaffPosts.SalesManager);
            })
            .Run();
        }

        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs.Result)
            {
                //保存转到详细页面之后饭后服务单列表
                if (args.ClosedArgs.Data == "Detail")
                {
                    UIContext.Current.ViewManager.ReplaceView(new Dispatching.MaintenanceBillListView());
                }
                if (args.ClosedArgs.ActiveArgs != null)
                {
                    //选择预约单
                    if (args.ClosedArgs.View is Pickers.BookingBillPicker)
                    {
                        _selectedBill = args.ClosedArgs.Data as WebRef.VBookingBill;
                        GetSelectedBookBill();
                    }
                    //选择客户
                    if (args.ClosedArgs.View is Pickers.VCustomerAccuratelyPicker)
                    {
                        selectCustomer = args.ClosedArgs.Data as WebRef.VCustomer;
                        GetSelectedCustomer(selectCustomer);
                    }
                    //选择服务项目
                    if (args.ClosedArgs.View is Pickers.SeviceItemPicker)
                    {
                        WebRef.VServiceItem selectServiceItem = args.ClosedArgs.Data as WebRef.VServiceItem;
                        GetSelectedServiceItem(selectServiceItem);
                        ClacTotalAmount();
                    }
                    //选择商品
                    if (args.ClosedArgs.View is Pickers.MaterialPicker)
                    {
                        WebRef.VMaterial vMaterial = args.ClosedArgs.Data as WebRef.VMaterial;
                        GetSelectedMaterial(vMaterial);
                        ClacTotalAmount();
                    }
                    //按仓库选择商品
                    if (args.ClosedArgs.View is Pickers.MaterialStockPicker)
                    {
                        WebRef.VStockMaterial vStockMaterial = args.ClosedArgs.Data as WebRef.VStockMaterial;
                        GetSelectedStockMaterial(vStockMaterial);
                        ClacTotalAmount();
                    }
                    //选择其他收费/优惠项目
                    if (args.ClosedArgs.View is Pickers.PayItemPicker)
                    {
                        WebRef.EPayItem PayItem = args.ClosedArgs.Data as WebRef.EPayItem;
                        GetSelectedPayItem(PayItem);
                        ClacTotalAmount();
                    }
                    //新建客户
                    if (args.ClosedArgs.View is Create.CreateCustomerView)
                    {
                        newCustomer = args.ClosedArgs.Data as WebRef.ECustomer;
                        GetNewCustomer();
                    }
                    //新增车辆
                    if (args.ClosedArgs.View is Create.CreateAutomobileView)
                    {
                        if (selectCustomer != null)
                        {
                            BindCarInfo(selectCustomer.Id);
                        }
                        if (newCustomer != null)
                        {
                            BindCarInfo(newCustomer.Id);
                        }
                    }
                }
            }
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("创建服务单");
        }
        #endregion

        #region Method
        /// <summary>
        /// //选择预约单
        /// </summary>
        private void GetSelectedBookBill()
        {
            if (_selectedBill != null)
            {
                GetCustomer(_selectedBill.CustomerId);
                txtQryBill.Text = string.Format("{0}-{1}-{2}", _selectedBill.CustomerName, _selectedBill.AutomobileLPN, _selectedBill.TargetDate.ToString("yyyy/MM/dd"));
                lblCustomerInfo.Text = string.Format("{0} 余额：{1}", _selectedBill.CustomerName, GetAsset(_selectedBill.CustomerId, Domain.Constant.AssetType.Balance).ToString());
                BindCarInfo(_selectedBill.CustomerId);
                if (_selectedBill.SalesManagerId != null)
                {
                    SearchLookUpEditUtil.SelectVStaffPosition(this.ctlLookUpSalesManager, new Guid(_selectedBill.SalesManagerId.ToString()));
                }
            }
        }
        /// <summary>
        /// 根据客户ID获取客户信息
        /// </summary>
        private void GetCustomer(Guid customerId)
        {
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<WebRef.VCustomer> result = new Service.GetService().GetCustomer(customerId);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        selectCustomer = result.Data;
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }
        /// <summary>
        /// 获取到新建的客户信息
        /// </summary>
        private void GetNewCustomer()
        {
            if (newCustomer != null)
            {
                selectCustomer = null;
                txtQryCustomer.Text = string.Format("{0}-{1}", newCustomer.Name, newCustomer.Telephone);
                lblCustomerInfo.Text = string.Format("{0} 余额：{1}", newCustomer.Name, GetAsset(newCustomer.Id, Domain.Constant.AssetType.Balance).ToString());
                BindCarInfo(newCustomer.Id);
                if (newCustomer.SalesManagerId != null)
                {
                    SearchLookUpEditUtil.SelectVStaffPosition(this.ctlLookUpSalesManager, new Guid(newCustomer.SalesManagerId.ToString()));
                }
            }
        }
        /// <summary>
        /// //选择客户
        /// </summary>
        /// <param name="selectCustomer"></param>
        private void GetSelectedCustomer(WebRef.VCustomer selectCustomer)
        {
            if (selectCustomer != null)
            {
                newCustomer = null;
                txtQryCustomer.Text = string.Format("{0}-{1}", selectCustomer.Name, selectCustomer.Telephone);
                lblCustomerInfo.Text = string.Format("{0} 余额：{1}", selectCustomer.Name, GetAsset(selectCustomer.Id, Domain.Constant.AssetType.Balance).ToString());
                BindCarInfo(selectCustomer.Id);
                SearchLookUpEditUtil.SelectVStaffPosition(this.ctlLookUpSalesManager, new Guid(selectCustomer.SalesManagerId.ToString()));
            }
        }
        /// <summary>
        /// 选择服务项目
        /// </summary>
        /// <param name="selectServiceItem"></param>
        private void GetSelectedServiceItem(WebRef.VServiceItem selectServiceItem)
        {
            if (selectServiceItem != null)
            {
                WebRef.EMaintenanceBillServiceItem item = new WebRef.EMaintenanceBillServiceItem(selectServiceItem.Name);
                item.ServiceItemId = selectServiceItem.Id;
                item.Price = selectServiceItem.Price;
                item.Hour = 1;
                item.Discount = 1;
                item.TechnicianCommission = selectServiceItem.TechnicianCommission;
                item.TechnicianCommissionType = selectServiceItem.TechnicianCommissionType;
                item.TechnicianId = null;
                item.SalesCommission = selectServiceItem.SalesCommission;
                item.SalesCommissionType = selectServiceItem.SalesCommissionType;
                item.SalesManagerId = null;
                if (listServiceItem.Exists((WebRef.EMaintenanceBillServiceItem s) => s.ServiceItemId == item.ServiceItemId ? true : false))
                {
                    UIContext.Current.ViewManager.ShowWarning("此服务项目已添加过，不能重复添加！");
                }
                else
                {
                    listServiceItem.Add(item);
                }
            }
            this.GCServiceProject.DataSource = null;
            this.GCServiceProject.DataSource = listServiceItem;
        }
        /// <summary>
        /// //选择商品
        /// </summary>
        /// <param name="vMaterial"></param>
        private void GetSelectedMaterial(WebRef.VMaterial vMaterial)
        {
            if (vMaterial != null)
            {
                WebRef.EMaintenanceBillMaterial item = new WebRef.EMaintenanceBillMaterial(vMaterial.Name);
                item.MaterialId = vMaterial.Id;
                item.Count = 1;
                item.Price = vMaterial.Price;
                item.Discount = 1;
                item.SalesCommission = vMaterial.SalesCommission;
                item.SalesCommissionType = vMaterial.SalesCommissionType;
                if (listMaterialItem.Exists((WebRef.EMaintenanceBillMaterial s) => s.MaterialId == item.MaterialId ? true : false))
                {
                    UIContext.Current.ViewManager.ShowWarning("此商品已添加过，不能重复添加！");
                }
                else
                {
                    listMaterialItem.Add(item);
                }
                this.GCGoodsData.DataSource = null;
                this.GCGoodsData.DataSource = listMaterialItem;
            }
        }
        /// <summary>
        /// 按仓库选择商品
        /// </summary>
        /// <param name="vStockMaterial"></param>
        private void GetSelectedStockMaterial(WebRef.VStockMaterial vStockMaterial)
        {
            if (vStockMaterial != null)
            {
                WebRef.EMaintenanceBillMaterial item = new WebRef.EMaintenanceBillMaterial(vStockMaterial.Name);
                item.MaterialId = vStockMaterial.Id;
                item.Count = 1;
                item.Price = vStockMaterial.Price;
                item.Discount = 1;
                item.SalesCommission = vStockMaterial.SalesCommission;
                item.SalesCommissionType = vStockMaterial.SalesCommissionType;
                if (listMaterialItem.Exists((WebRef.EMaintenanceBillMaterial s) => s.MaterialId == item.MaterialId ? true : false))
                {
                    UIContext.Current.ViewManager.ShowWarning("此商品已添加过，不能重复添加！");
                }
                else
                {
                    listMaterialItem.Add(item);
                }
                this.GCGoodsData.DataSource = null;
                this.GCGoodsData.DataSource = listMaterialItem;
            }
        }
        /// <summary>
        /// 选择其他收费/优惠项目
        /// </summary>
        /// <param name="PayItem"></param>
        private void GetSelectedPayItem(WebRef.EPayItem PayItem)
        {
            if (PayItem != null)
            {
                WebRef.EMaintenanceBillPayItem item = new WebRef.EMaintenanceBillPayItem(PayItem.Name);
                item.PayItemId = PayItem.Id;
                item.PayItemType = PayItem.Type;
                item.Amount = PayItem.Amount;
                if (listPayItem.Exists((WebRef.EMaintenanceBillPayItem s) => s.PayItemId == item.PayItemId ? true : false))
                {
                    UIContext.Current.ViewManager.ShowWarning("此项目已添加过，不能重复添加！");
                }
                else
                {
                    listPayItem.Add(item);
                }
                this.GCOther.DataSource = null;
                this.GCOther.DataSource = listPayItem;
            }
        }
        private decimal GetAsset(Guid Id, int assetType)
        {
            decimal balance = 0;
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<decimal> result = new Service.GetService().GetAsset(Id, assetType);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        balance = result.Data;
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
            return balance;
        }
        /// <summary>
        /// 计算总费用
        /// </summary>
        private void ClacTotalAmount()
        {
            string strOutMess = "";
            decimal total = Calculation.MaintanceBillCalculation.Calc(
                GetListServiceItem() == null ? null : GetListServiceItem().ToArray(),
                GetListMaterialItem() == null ? null : GetListMaterialItem().ToArray(),
                GetListPayItem() == null ? null : GetListPayItem().ToArray(),
                false,
                out strOutMess);
            lblTotalInfo.Text = string.Format("订单总计：{0}={1}", total.ToString(), strOutMess);
        }
        /// <summary>
        /// 根据客户ID查找车辆信息
        /// </summary>
        /// <param name="customerID"></param>
        private void BindCarInfo(Guid customerID)
        {
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ListResult<WebRef.VAutomobile> result = new Service.QueryService().QueryAutomobileList(customerID);
                this.BeginInvoke(new Action<ListResult<WebRef.VAutomobile>>((p) =>
                {
                    this.HideMask();
                    if (p.IsSuccess)
                    {
                        this.GCCarInfo.DataSource = null;
                        this.GVCarInfo.FocusedRowHandle = -1;
                        this.GCCarInfo.DataSource = p.Data.Items;
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError("查找车辆信息失败！");
                    }
                }), result);
            });
        }
        /// <summary>
        /// 获取已选服务项目列表
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EMaintenanceBillServiceItem> GetListServiceItem()
        {
            List<WebRef.EMaintenanceBillServiceItem> listItem = this.GVServiceProject.DataSource as List<WebRef.EMaintenanceBillServiceItem>;
            if (listItem != null)
            {
                for (int i = 0; i < listItem.Count; i++)
                {
                    if (listItem[i].Hour <= 0)
                    {
                        UIContext.Current.ViewManager.ShowWarning("服务项目工时应大于0！");
                        return null;
                    }
                }
            }
            return listItem;
        }
        /// <summary>
        /// 获取已选商品
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EMaintenanceBillMaterial> GetListMaterialItem()
        {
            List<WebRef.EMaintenanceBillMaterial> listItem = this.GCGoodsData.DataSource as List<WebRef.EMaintenanceBillMaterial>;
            return listItem;
        }
        /// <summary>
        /// 获取收费/优惠项目
        /// </summary>
        /// <returns></returns>
        private List<WebRef.EMaintenanceBillPayItem> GetListPayItem()
        {
            List<WebRef.EMaintenanceBillPayItem> listItem = this.GVOther.DataSource as List<WebRef.EMaintenanceBillPayItem>;
            return listItem;
        }
        private bool ValidateData()
        {
            string message = null;
            if (selectCustomer == null && newCustomer == null)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择预约单或查询客户信息！也可点击新建客户按钮新建客户！");
                return false;
            }
            if (entity == null)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择车辆信息！");
                return false;
            }
            if (!ValidationManager.Validate(this, out message))
            {
                UIContext.Current.ViewManager.ShowError(message);
                return false;
            }
            if (listServiceItem.Count == 0 && listMaterialItem.Count == 0)
            {
                UIContext.Current.ViewManager.ShowWarning("请选择服务项目或商品配件！");
                return false;
            }
            if (GetListServiceItem() == null && GetListMaterialItem() == null)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 创建服务单
        /// </summary>
        private void CreateStockIncreaseBill()
        {
            WebRef.EMaintenanceBill bill = new WebRef.EMaintenanceBill();
            bill.BusinessId = new Guid(ModuleContext.Current.BusinessId.ToString());
            bill.StationId = new Guid(ModuleContext.Current.StationId.ToString());
            if (_selectedBill != null)
            {
                bill.BookingBillId = _selectedBill.Id;
            }
            bill.CustomerId = selectCustomer == null ? newCustomer.Id : selectCustomer.Id;
            bill.AutomobileId = (this.GVCarInfo.GetFocusedRow() as WebRef.VAutomobile).Id;
            WebRef.VStaffPosition item = SearchLookUpEditUtil.GetSelectedValue<WebRef.VStaffPosition>(ctlLookUpSalesManager);
            if (item != null)
            {
                bill.SalesManagerId = item.StaffId;
            }
            if (string.IsNullOrEmpty(txtCarOutDate.Text) == false)
            {
                bill.EstimatedDeliveryDate = Convert.ToDateTime(txtCarOutDate.Text.Trim());
            }
            bill.OilMass = Domain.Constant.OilMass.GetValue(this.ctlSearchLookUpEditOilMass.GetSelectedValue<Domain.IntCodeTextItem>().GetCode());
            if (!string.IsNullOrEmpty(this.txtKM.Text.Trim()))
            {
                bill.RunningKilometers = int.Parse(txtKM.Text.Trim());
            }
            bill.Memo = this.txtPickRemark.Text.Trim();
            bill.VIN = this.txtLPN.Text.Trim();
            bill.EIN = this.txtEngineNo.Text.Trim();
            if (!string.IsNullOrEmpty(this.txtNextPro.Text.Trim()))
            {
                bill.NextMaintenanceDate = Convert.ToDateTime(this.txtNextPro.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtNextYear.Text.Trim()))
            {
                bill.NextAnnualSurveyDate = Convert.ToDateTime(this.txtNextYear.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtInsuranceExpir.Text.Trim()))
            {
                bill.InsuranceExpirationDate = Convert.ToDateTime(this.txtInsuranceExpir.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtChangeTime.Text.Trim()))
            {
                bill.NextReplaceTireDate = Convert.ToDateTime(this.txtChangeTime.Text.Trim());
            }
            WebRef.EMasterDataItem masterDataItem = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.lupInsuranceCompany);
            if (masterDataItem != null)
            {
                bill.InsuranceCompany = masterDataItem.Code;
            }
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<WebRef.EMaintenanceBill> result = new Service.CreateService().CreateMaintenanceBill(
                    bill,
                    GetListServiceItem() == null ? null : GetListServiceItem().ToArray<WebRef.EMaintenanceBillServiceItem>(),
                    GetListMaterialItem() == null ? null : GetListMaterialItem().ToArray<WebRef.EMaintenanceBillMaterial>(),
                    GetListPayItem() == null ? null : GetListPayItem().ToArray<WebRef.EMaintenanceBillPayItem>().ToArray<WebRef.EMaintenanceBillPayItem>());
                this.BeginInvoke(new Action<SingleResult<WebRef.EMaintenanceBill>>((p) =>
                {
                    this.HideMask();
                    if (p.IsSuccess)
                    {
                        UIContext.Current.ViewManager.ReplaceView(new Dispatching.MaintenanceBillDetailView(p.Data.Id));
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(p.Message);
                        _promise.Reject();
                    }
                }), result);
            });
        }
        #endregion

        #region Action
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, object e)
        {
            try
            {
                if (ValidateData())
                {
                    CreateStockIncreaseBill();
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 一键派工&领料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDispacting_Click(object sender, object e)
        {

        }
        /// <summary>
        /// 查找预约单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQryBill_Click(object sender, EventArgs e)
        {
            this.txtQryCustomer.Text = "";
            UIContext.Current.ViewManager.PopupView(new Pickers.BookingBillPicker(new Domain.IntCodeTextItem[] { Domain.Constant.BookingBillStatus.NormalItem }, false),
                new PopupViewArgs("选择预约单"));
        }
        /// <summary>
        /// 新建客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddCustomer_Click(object sender, EventArgs e)
        {
            UIContext.Current.ViewManager.PopupView(new Create.CreateCustomerView(),
              new PopupViewArgs("新建客户"));
        }
        /// <summary>
        /// 查找客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQryCustomer_Click(object sender, EventArgs e)
        {
            this.txtQryBill.Text = "";
            UIContext.Current.ViewManager.PopupView(new Pickers.VCustomerAccuratelyPicker(),
                new PopupViewArgs("选择客户"));
        }
        /// <summary>
        /// 新增车辆信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddCar_Click(object sender, EventArgs e)
        {
            if (selectCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Create.CreateAutomobileView(selectCustomer), new PopupViewArgs("新增车辆"));
            }
            if (newCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Create.CreateAutomobileView(newCustomer), new PopupViewArgs("新增车辆"));
            }
        }
        /// <summary>
        /// 选择服务项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddProject_Click(object sender, EventArgs e)
        {
            UIContext.Current.ViewManager.PopupView(new Pickers.SeviceItemPicker(),
               new PopupViewArgs("选择服务项目"));
        }
        /// <summary>
        /// 服务项目计算应收费用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVServiceProject_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                if (this.GVServiceProject.FocusedColumn == e.Column)
                {
                    if (e.Column.FieldName == "Hour" || e.Column.FieldName == "Discount")
                    {
                        WebRef.EMaintenanceBillServiceItem model = this.GVServiceProject.GetRow(e.Column.View.FocusedRowHandle) as WebRef.EMaintenanceBillServiceItem;
                        this.GVServiceProject.SetRowCellValue(e.Column.View.FocusedRowHandle, "ActualAmount", model.ActualAmount);
                        this.GVGoodsData.SetRowCellValue(e.Column.View.FocusedRowHandle, "TechnicianCommissionAmountText", model.TechnicianCommissionAmountText);
                        this.GVGoodsData.SetRowCellValue(e.Column.View.FocusedRowHandle, "SalesCommissionAmountText", model.SalesCommissionAmountText);
                        ClacTotalAmount();
                    }
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 移除选择的服务项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEditOperate_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Caption == "移除")
                {
                    WebRef.EMaintenanceBillServiceItem item = this.GVServiceProject.GetRow(GVServiceProject.FocusedRowHandle) as WebRef.EMaintenanceBillServiceItem;
                    listServiceItem.Remove(item);
                    if (listServiceItem.Count == 0)
                    {
                        this.GCServiceProject.DataSource = null;
                    }
                    else
                    {
                        this.GCServiceProject.DataSource = null;
                        this.GCServiceProject.DataSource = listServiceItem;
                    }
                    ClacTotalAmount();
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 选择商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddGoods_Click(object sender, EventArgs e)
        {
            UIContext.Current.ViewManager.PopupView(new Pickers.MaterialPicker(Domain.Constant.CommonStatus.Enabled),
             new PopupViewArgs("选择商品"));
        }
        /// <summary>
        /// 按仓库选择商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectMaterialByWareHouse_Click(object sender, EventArgs e)
        {
            UIContext.Current.ViewManager.PopupView(new Pickers.MaterialStockPicker(), new PopupViewArgs("按仓库选择商品"));
        }
        /// <summary>
        /// 商品配件计算应收费用&销售提成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVGoodsData_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                if (this.GVGoodsData.FocusedColumn == e.Column)
                {
                    if (e.Column.FieldName == "Count" || e.Column.FieldName == "Discount")
                    {
                        WebRef.EMaintenanceBillMaterial model = this.GVGoodsData.GetRow(e.Column.View.FocusedRowHandle) as WebRef.EMaintenanceBillMaterial;
                        this.GVGoodsData.SetRowCellValue(e.Column.View.FocusedRowHandle, "ActualAmount", model.ActualAmount);
                        this.GVGoodsData.SetRowCellValue(e.Column.View.FocusedRowHandle, "SalesCommissionAmountText", model.SalesCommissionAmountText);
                        ClacTotalAmount();
                    }
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 移除已选商品配件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEditGOperate_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Caption == "移除")
                {
                    WebRef.EMaintenanceBillMaterial item = this.GVGoodsData.GetRow(GVGoodsData.FocusedRowHandle) as WebRef.EMaintenanceBillMaterial;
                    listMaterialItem.Remove(item);
                    if (listMaterialItem.Count == 0)
                    {
                        this.GCGoodsData.DataSource = null;
                    }
                    else
                    {
                        this.GCGoodsData.DataSource = null;
                        this.GCGoodsData.DataSource = listMaterialItem;
                    }
                    ClacTotalAmount();
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 选择其他收费/优惠项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddOther_Click(object sender, EventArgs e)
        {
            UIContext.Current.ViewManager.PopupView(new Pickers.PayItemPicker(),
             new PopupViewArgs("选择其他收费/优惠"));
        }
        /// <summary>
        /// 移除付费项目
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEditOtherOperate_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                if (e.Button.Caption == "移除")
                {
                    WebRef.EMaintenanceBillPayItem item = this.GVOther.GetRow(GVOther.FocusedRowHandle) as WebRef.EMaintenanceBillPayItem;
                    listPayItem.Remove(item);
                    if (listPayItem.Count == 0)
                    {
                        this.GCOther.DataSource = null;
                    }
                    else
                    {
                        this.GCOther.DataSource = null;
                        this.GCOther.DataSource = listPayItem;
                    }
                    ClacTotalAmount();
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 根据选中的车辆获取其详细信息显示在右侧
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GVCarInfo_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (this.GVCarInfo.FocusedRowHandle > -1)
                {
                    entity = GVCarInfo.GetRow(GVCarInfo.FocusedRowHandle) as WebRef.VAutomobile;
                    this.txtLPN.Text = entity.VIN;
                    this.txtEngineNo.Text = entity.EIN;
                    this.txtNextPro.Text = string.Format("{0:yyyy/MM/dd}", entity.NextMaintenanceDate);
                    this.txtNextYear.Text = string.Format("{0:yyyy/MM/dd}", entity.NextAnnualSurveyDate);
                    this.txtInsuranceExpir.Text = string.Format("{0:yyyy/MM/dd}", entity.InsuranceExpirationDate);
                    SearchLookUpEditUtil.SelectEMasterDataItem(this.lupInsuranceCompany, entity.InsuranceCompany);
                }
            }
            catch (Exception ex)
            {
                UIContext.Current.ViewManager.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 客户详细信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCustomerInfo_Click(object sender, EventArgs e)
        {
            if (selectCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Show.ShowCustomerDetailView(selectCustomer.Id), new PopupViewArgs("查看客户详细信息"));
            }
            if (newCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Show.ShowCustomerDetailView(newCustomer.Id), new PopupViewArgs("查看客户详细信息"));
            }
        }
        /// <summary>
        /// 修改客户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditCustomer_Click(object sender, EventArgs e)
        {
            if (selectCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Edit.UpdateCustomerView(selectCustomer.Id ), new PopupViewArgs("修改客户"));
            }
            if (newCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Edit.UpdateCustomerView(newCustomer.Id), new PopupViewArgs("修改客户"));
            }
        }
        /// <summary>
        /// 账户充值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRecharge_Click(object sender, EventArgs e)
        {
            if (selectCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Create.CreateRechargeBillView(selectCustomer), new PopupViewArgs("账户充值"));
            }
            if (newCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Create.CreateRechargeBillView(newCustomer), new PopupViewArgs("账户充值"));
            }
        }
        /// <summary>
        /// 套餐购买
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBuyPackage_Click(object sender, EventArgs e)
        {
            if (selectCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Create.CreatePackagePurchaseBillView(selectCustomer), new PopupViewArgs("套餐购买"));
            }
            if (newCustomer != null)
            {
                UIContext.Current.ViewManager.PopupView(new Create.CreatePackagePurchaseBillView(newCustomer), new PopupViewArgs("套餐购买"));
            }
        }
        #endregion
    }
}
